<template>
  <view class="h5-ad-reward-container">
    <!-- 广告奖励卡片 -->
    <view class="ad-card" @click="handleWatchAd">
      <view class="ad-header">
        <view class="ad-icon">🎬</view>
        <view class="ad-title">观看广告获得积分</view>
        <view class="ad-platform">{{ platformName }}</view>
      </view>
      
      <view class="ad-content">
        <view class="reward-info">
          <text class="reward-text">完整观看广告可获得</text>
          <text class="reward-points">{{ rewardPoints }}</text>
          <text class="reward-unit">积分</text>
        </view>
        
        <view class="ad-stats">
          <text class="stats-text">今日已观看: {{ todayCount }}/{{ dailyLimit }}</text>
        </view>
      </view>
      
      <view class="ad-footer">
        <button 
          class="watch-btn" 
          :class="{ 'disabled': !canWatch || isLoading }"
          :disabled="!canWatch || isLoading"
          @click.stop="handleWatchAd"
        >
          <text v-if="isLoading">{{ loadingText }}</text>
          <text v-else-if="!canWatch">今日已达上限</text>
          <text v-else>立即观看</text>
        </button>
      </view>
    </view>
    
    <!-- 广告说明 -->
    <view class="ad-tips">
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">需要完整观看广告才能获得积分奖励</text>
      </view>
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">每日最多可观看{{ dailyLimit }}次广告</text>
      </view>
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">积分将在观看完成后立即到账</text>
      </view>
      <view class="tip-item">
        <text class="tip-icon">•</text>
        <text class="tip-text">支持多个广告平台，确保广告供应</text>
      </view>
    </view>
    
    <!-- 加载遮罩 -->
    <view v-if="showLoadingMask" class="loading-mask">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{ loadingText }}</text>
        <button v-if="showCancelBtn" class="cancel-btn" @click="cancelLoading">取消</button>
      </view>
    </view>
    
    <!-- 结果弹窗 -->
    <view v-if="showResultModal" class="result-modal">
      <view class="result-content">
        <view class="result-icon">
          <text v-if="adResult.success">🎉</text>
          <text v-else>😔</text>
        </view>
        <view class="result-title">{{ adResult.title }}</view>
        <view class="result-message">{{ adResult.message }}</view>
        <button class="result-btn" @click="closeResultModal">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import adManager from '@/utils/adManager.js'
import { getCurrentAdPlatform, getAdPlatformConfig } from '@/config/h5AdConfig.js'

export default {
  name: 'H5AdReward',
  data() {
    return {
      rewardPoints: 1,
      todayCount: 0,
      dailyLimit: 50,
      canWatch: true,
      isLoading: false,
      loadingText: '准备广告中...',
      showLoadingMask: false,
      showCancelBtn: false,
      showResultModal: false,
      adResult: {
        success: false,
        title: '',
        message: ''
      },
      platformName: '广告平台',
      loadingTimer: null
    }
  },
  
  mounted() {
    this.initAdPlatform()
    this.loadAdLimit()
  },
  
  beforeDestroy() {
    if (this.loadingTimer) {
      clearTimeout(this.loadingTimer)
    }
  },
  
  methods: {
    /**
     * 初始化广告平台信息
     */
    initAdPlatform() {
      const platform = getCurrentAdPlatform()
      const config = getAdPlatformConfig(platform)
      this.platformName = config ? config.name : '广告平台'
    },
    
    /**
     * 加载广告限制信息
     */
    async loadAdLimit() {
      try {
        const limitInfo = await adManager.getTodayAdLimit()
        this.todayCount = limitInfo.todayCount || 0
        this.dailyLimit = limitInfo.dailyLimit || 50
        this.canWatch = limitInfo.canWatch || false
        this.rewardPoints = limitInfo.rewardPoints || 1
      } catch (error) {
        console.error('加载广告限制失败:', error)
        this.$emit('error', error)
      }
    },
    
    /**
     * 处理观看广告
     */
    async handleWatchAd() {
      if (!this.canWatch || this.isLoading) {
        return
      }
      
      // 检查是否可以观看广告
      const canWatch = await adManager.canWatchAd()
      if (!canWatch) {
        this.showToast('今日观看次数已达上限')
        return
      }
      
      this.startLoading()
      
      try {
        // 显示激励视频广告
        const result = await adManager.showRewardedVideoAd()
        
        this.stopLoading()
        
        if (result.completed) {
          // 观看完成，获得奖励
          this.adResult = {
            success: true,
            title: '恭喜获得奖励！',
            message: `您获得了 ${result.reward.points} 积分`
          }
          
          // 更新观看次数
          this.todayCount++
          this.canWatch = this.todayCount < this.dailyLimit
          
          // 触发积分更新事件
          this.$emit('reward-earned', result.reward)
          
        } else {
          // 未完整观看
          this.adResult = {
            success: false,
            title: '未获得奖励',
            message: result.message || '需要完整观看广告才能获得积分'
          }
        }
        
        this.showResultModal = true
        
      } catch (error) {
        this.stopLoading()
        
        console.error('观看广告失败:', error)
        
        this.adResult = {
          success: false,
          title: '广告播放失败',
          message: this.getErrorMessage(error)
        }
        
        this.showResultModal = true
      }
    },
    
    /**
     * 开始加载
     */
    startLoading() {
      this.isLoading = true
      this.showLoadingMask = true
      this.loadingText = '准备广告中...'
      this.showCancelBtn = false
      
      // 3秒后显示取消按钮
      this.loadingTimer = setTimeout(() => {
        this.showCancelBtn = true
        this.loadingText = '广告加载中...'
      }, 3000)
    },
    
    /**
     * 停止加载
     */
    stopLoading() {
      this.isLoading = false
      this.showLoadingMask = false
      this.showCancelBtn = false
      
      if (this.loadingTimer) {
        clearTimeout(this.loadingTimer)
        this.loadingTimer = null
      }
    },
    
    /**
     * 取消加载
     */
    cancelLoading() {
      this.stopLoading()
      this.showToast('已取消广告加载')
    },
    
    /**
     * 关闭结果弹窗
     */
    closeResultModal() {
      this.showResultModal = false
    },
    
    /**
     * 获取错误信息
     */
    getErrorMessage(error) {
      const message = error.message || '未知错误'
      
      // 根据错误类型返回友好的提示
      if (message.includes('网络')) {
        return '网络连接失败，请检查网络后重试'
      } else if (message.includes('加载')) {
        return '广告加载失败，请稍后重试'
      } else if (message.includes('初始化')) {
        return '广告服务初始化失败，请刷新页面重试'
      } else {
        return message
      }
    },
    
    /**
     * 显示提示
     */
    showToast(message) {
      // 在H5环境中使用原生提示
      if (typeof uni !== 'undefined' && uni.showToast) {
        uni.showToast({
          title: message,
          icon: 'none'
        })
      } else {
        alert(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.h5-ad-reward-container {
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.ad-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  color: white;
}

.ad-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  
  .ad-icon {
    font-size: 32px;
    margin-right: 12px;
  }
  
  .ad-title {
    flex: 1;
    font-size: 20px;
    font-weight: bold;
  }
  
  .ad-platform {
    font-size: 12px;
    opacity: 0.8;
    background: rgba(255, 255, 255, 0.2);
    padding: 4px 8px;
    border-radius: 8px;
  }
}

.ad-content {
  margin-bottom: 20px;
}

.reward-info {
  display: flex;
  align-items: baseline;
  margin-bottom: 12px;
  
  .reward-text {
    font-size: 16px;
    opacity: 0.9;
  }
  
  .reward-points {
    font-size: 32px;
    font-weight: bold;
    color: #FFD700;
    margin: 0 8px;
  }
  
  .reward-unit {
    font-size: 16px;
    opacity: 0.9;
  }
}

.ad-stats {
  opacity: 0.8;
  font-size: 14px;
}

.ad-footer {
  display: flex;
  justify-content: center;
}

.watch-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 24px;
  padding: 12px 32px;
  color: white;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:not(.disabled):hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
  }
  
  &:not(.disabled):active {
    transform: translateY(0);
  }
  
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background: rgba(255, 255, 255, 0.1);
  }
}

.ad-tips {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .tip-icon {
    color: #667eea;
    font-weight: bold;
    margin-right: 8px;
    line-height: 1.5;
  }
  
  .tip-text {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    flex: 1;
  }
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  border-radius: 16px;
  padding: 32px;
  text-align: center;
  min-width: 200px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  display: block;
}

.cancel-btn {
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  
  &:hover {
    background: #e9e9e9;
  }
}

.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.result-content {
  background: white;
  border-radius: 16px;
  padding: 32px;
  text-align: center;
  min-width: 280px;
  max-width: 400px;
}

.result-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.result-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.result-message {
  font-size: 16px;
  color: #666;
  margin-bottom: 24px;
  line-height: 1.5;
}

.result-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  
  &:hover {
    background: #5a6fd8;
  }
}
</style>